package com.sgb.kjwl.view.ui.activity.enterprise;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityProfessionalTeamDetailBinding;
import com.sgb.kjwl.di.enterprise.DaggerEnterpriseComponent;
import com.sgb.kjwl.di.enterprise.EnterpriseModule;
import com.sgb.kjwl.model.entity.enterprise.ProfessionalTeamDetailEntity2;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.swgk.core.util.UiUtil;
import com.sgb.kjwl.view.event.CustomViewsInfo;
import com.sgb.kjwl.view.ui.fragment.enterprise.PsTeamDetailDescribeFragment;
import com.sgb.kjwl.view.ui.fragment.enterprise.PsTeamDetailServiceQuoteFragment;
import com.sgb.kjwl.view.ui.fragment.enterprise.PsTeamDetailTalentFragment;
import com.sgb.kjwl.view.ui.fragment.enterprise.TeamIntelligenceFragment;
import com.sgb.link.view.widget.ExpandedTextView;
import com.sgb.kjwl.viewmodel.enterprise.ProfessionalTeamDetailModel;
import com.stx.xhb.androidx.XBanner;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.ClickUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class ProfessionalTeamDetailActivity extends AppActivity {

    private ActivityProfessionalTeamDetailBinding binding;
    private boolean flag = false;
    private int bannerCount;
    private long id;

    private ProfessionalTeamDetailEntity2 teamDetailEntity = new ProfessionalTeamDetailEntity2();
    @Inject
    ProfessionalTeamDetailModel professionalTeamDetailModel;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseComponent.builder().appComponent(appComponent)
                .enterpriseModule(new EnterpriseModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        super.initView();
        binding = DataBindingUtil.setContentView(this, R.layout.activity_professional_team_detail);
        binding.setModel(professionalTeamDetailModel);
        id = getIntent().getLongExtra("id", 0);

        binding.setPtd(new ProfessionalTeamDetailEntity2());

        binding.tvAttentionGoods.setOnClickListener(this);
        binding.bottomView.setOnClickListener(this);
        binding.llEnter.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_attention_goods://关注
                flag = !flag;
                setuserFocusStatus(flag);
                break;
            case R.id.bottom_view://联系商家
                if (!ClickUtils.isDoubleClick()) {
                    if (DialogHelper.checkLogin()) {
                        DialogHelper.showDialog(ProfessionalTeamDetailActivity.this,
                                "确认呼叫",
                                teamDetailEntity.getLinkMan() + ":" + teamDetailEntity.getPhone(),
                                "确定", new DialogFunction() {
                                    @Override
                                    public void normalRoundDialog() {
                                        ActivityJump.jumpToPhone(ProfessionalTeamDetailActivity.this, teamDetailEntity.getPhone());
                                    }
                                });
                    } else {
                        DialogHelper.showLoginDialogNew(this, 0, "温馨提示", "登录后可拨打电话,去登录", "登录");
                    }
                }
                break;
            case R.id.ll_enter://进入企业
                if (!ClickUtils.isDoubleClick()) {

                }
                break;
        }
    }

    public void setuserFocusStatus(boolean data) {
        if (data) {
            binding.tvAttentionGoods.setBackgroundResource(R.drawable.bgg_lg);
            binding.tvAttentionGoods.setText("已关注");
            binding.tvAttentionGoods.setTextColor(getResources().getColor(R.color.alertdialog_gray));
        } else {
            binding.tvAttentionGoods.setBackgroundResource(R.drawable.bgw_lb);
            binding.tvAttentionGoods.setText("关注");
            binding.tvAttentionGoods.setTextColor(getResources().getColor(R.color.alertdialog_blue));
        }
    }

    /**
     * 专业团队详情内
     */
    private void showTabLayout() {
        binding.tablayout2.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(ProfessionalTeamDetailActivity.this).inflate(R.layout.item_textview_4, null);
                TextView selectTextView = linearLayout.findViewById(R.id.tab_item_textview);
                selectTextView.setText(tab.getText());
                tab.setCustomView(linearLayout);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                tab.setCustomView(null);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        String[] titles = {"详情描述", "团队资质", "优秀人才", "服务案例"};
        ArrayList<Fragment> mFragments = new ArrayList<>();
        mFragments.add(PsTeamDetailDescribeFragment.newInstance(teamDetailEntity));
        mFragments.add(TeamIntelligenceFragment.newInstance(String.valueOf(teamDetailEntity.getId())));
        mFragments.add(PsTeamDetailTalentFragment.newInstance(String.valueOf(teamDetailEntity.getId())));
        mFragments.add(PsTeamDetailServiceQuoteFragment.newInstance(String.valueOf(teamDetailEntity.getId())));
        SlidingFragmentPagerAdapter pagerAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, titles);
        binding.vpProfessionalTeamDetail.setCurrentItem(0);
        binding.vpProfessionalTeamDetail.setOffscreenPageLimit(titles.length);
        binding.vpProfessionalTeamDetail.setAdapter(pagerAdapter);
        binding.tablayout2.setupWithViewPager(binding.vpProfessionalTeamDetail);
        binding.vpProfessionalTeamDetail.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(binding.tablayout2));
        binding.vpProfessionalTeamDetail.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                binding.vpProfessionalTeamDetail.resetHeight(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        binding.tablayout2.getTabAt(0).select();
    }

    /**
     * 提供子fragment调用方法，解决listview高度不自适应出现多余空白
     */
    public void setChildObjectForPosition(View view, int position) {
        binding.vpProfessionalTeamDetail.setObjectForPosition(view, position);
    }

    @SuppressLint("SetTextI18n")
    public void setShowDetails(ProfessionalTeamDetailEntity2 entity) {
        if (entity==null)return;
        binding.setPtd(entity);
        this.teamDetailEntity = entity;
        showTabLayout();

        List<String> imageList = new ArrayList<>();
        if (entity.getImages().getList()!=null&&entity.getImages().getList().size()>0){
            for (ProfessionalTeamDetailEntity2.ImagesBean.ListBean listBean : entity.getImages().getList()) {
                imageList.add(listBean.getUpload_pic());
            }
            int size = imageList.size();
            bannerCount = size;
            if (bannerCount == 1 || bannerCount == 0) {
                binding.tvPosition.setText(1 + "");
                binding.tvCount.setText(1 + "");
                binding.rlBottom.setVisibility(View.GONE);
            }

            setBannerView (imageList);
        } else if (entity.getImages().getList()!=null&&entity.getImages().getList().size() == 0) {//没有数据时添加默认图
            imageList.add("");
            binding.rlBottom.setVisibility(View.GONE);
            setBannerView(imageList);
        }
        List<ProfessionalTeamDetailEntity2.ServiceCityBean> citys = entity.getServiceCity();
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < citys.size(); i++) {
            ProfessionalTeamDetailEntity2.ServiceCityBean city = citys.get(i);
            if (i == citys.size() - 1) {
                stringBuilder.append(city.getArea_name());
            } else {
                stringBuilder.append(city.getArea_name()).append("/");
            }
        }
        binding.tvServiceForCity.setText(TextUtils.isEmpty(stringBuilder.toString()) ? "/" : stringBuilder.toString());
        Glide.with(this).load(entity.getLogo()).apply(new RequestOptions()
                .placeholder(R.mipmap.wulogo_team_heand)
                .fallback(R.mipmap.wulogo_team_heand)
                .error(R.mipmap.wulogo_team_heand))
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(binding.ivLogo);

        new ExpandedTextView().showTextPick(binding.tvWorkPrimary, binding.tvWorkPrimaryExpand);
        new ExpandedTextView().showTextPick(binding.tvRegion, binding.tvRegionExpand);


        StringBuilder builder = new StringBuilder();
        if (!TextUtils.isEmpty(entity.getBusiness_address())) {
            builder.append(entity.getBusiness_address());
        }
        if (!TextUtils.isEmpty(entity.getBusiness_address_sup())) {
            builder.append(entity.getBusiness_address_sup());
        }
        if (builder.toString().equals("")) {
            binding.tvRegion.setText("/");
        } else {
            binding.tvRegion.setText(builder.toString());
        }
    }

    private void setBannerView (List<String> imageList){
        List<CustomViewsInfo> imageListNo = new ArrayList<>();
        if (imageList.size() > 0 && imageList.get(0).equals("")) {
            imageListNo.add(new CustomViewsInfo(R.mipmap.morentu_jingyingbang_detail));
        } else {
            binding.banner.setBackground(getResources().getDrawable(R.color.white));
            for (int i = 0; i< imageList.size(); i++) {
                imageListNo.add(new CustomViewsInfo(imageList.get(i)));
            }
        }
        binding.banner.setBannerData(imageListNo);
        //加载广告图片
        binding.banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                if (imageList.size() > 0 && imageList.get(0).equals("")) {
                    Glide.with(UiUtil.getContext()).load(getResources().getDrawable(R.mipmap.morentu_jingyingbang_detail)).into((ImageView)view);
                } else {
                    Glide.with(UiUtil.getContext()).load(imageList.get(position)).into((ImageView)view);
                    ((ImageView) view).setScaleType(ImageView.ScaleType.FIT_CENTER);
                }
            }
        });
    }



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        professionalTeamDetailModel.getTeamQueryDetail(id);
    }
}
